<?php

namespace apiend\modules\dynamic\models;

use Yii;
use common\base\Model;
use yii\db\Exception;
use common\models\dynamic\DynamicComment;
use common\models\dynamic\DynamicStats;

class DynamicCommentForm extends Model {

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @name $dynamic_id
     * @var integer 被回复或评论的动态ID
     */
    public $dynamic_id;

    /**
     * @name $content
     * @var string 回复或评论内容
     */
    public $content;

    public function rules() {
        return [
            [['user_id', 'dynamic_id'], 'integer'],
            ['content', 'required', 'message' => '{attribute}不能为空'],
            [['content'], 'string', 'max' => 255],
        ];
    }

    public function attributeLabels() {
        return [
            'content' => '回复内容'
        ];
    }

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('发布提交失败');
        }

        $model = new DynamicComment();
        $model->attributes = [
            'user_id' => $this->user_id,
            'dynamic_id' => $this->dynamic_id,
            'content' => $this->content,
        ];

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception('回复内容保存时失败！' . print_r($model->errors, true));
            }
            $stats = DynamicStats::findOrNew([
                'dynamic_id' => $model->id,
            ]);
            if (!$stats->save()) {
                throw new Exception('创建动态回复初始化失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
            return false;
        }

        return $model->toArray();
    }

}
